package com.sanjiahantang.youjiaclient.module.login.views.impl;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.youjiaclient.R;
import com.sanjiahantang.youjiaclient.base.BaseMvpActivity;
import com.sanjiahantang.youjiaclient.config.ConfigValue;
import com.sanjiahantang.youjiaclient.http.BaseDelegate;
import com.sanjiahantang.youjiaclient.http.ExceptionHelper;
import com.sanjiahantang.youjiaclient.http.OkHttpClientManager;
import com.sanjiahantang.youjiaclient.module.common.beans.StringBean;
import com.sanjiahantang.youjiaclient.module.common.views.impl.WebActivity;
import com.sanjiahantang.youjiaclient.module.login.presenters.LoginPresenter;
import com.sanjiahantang.youjiaclient.module.login.views.LoginView;
import com.sanjiahantang.youjiaclient.utils.CheckUtil;
import com.sanjiahantang.youjiaclient.utils.KeyBoardUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import static com.sanjiahantang.youjiaclient.config.StaticValue.RESPONSE_CODE_SUC;

/**
 * Created by sks on 2015/9/17.
 * 注册
 */
public class RegisterActivity extends BaseMvpActivity<LoginView, LoginPresenter> implements View.OnClickListener, LoginView {
    private Context context;
    private EditText editUserName, editPassword, editCode,editAgain;
    private String userName, password;//,e_mail,again;
    private TextView btnRegister, txtCode,tvContract;
    private CheckBox cbContract;
    private View panelContract;
    private TextView title;
    private ImageView back;
    private FrameLayout left;
    private int startime = 60;
    private Timer timer;
    @Override
    public LoginPresenter initPresenter() {
        return new LoginPresenter();
    }
    @Override
    public void initView() {
        setContentView(R.layout.activity_register);
        context = this;
        title = (TextView) findViewById(R.id.title);
        back = (ImageView) findViewById(R.id.back);
        left = (FrameLayout) findViewById(R.id.fl_Left);
        back.setBackgroundResource(R.drawable.i_back_black);
        title.setText("注册");
        left.setOnClickListener(this);
        editUserName = (EditText) findViewById(R.id.editUserName);
        //editEmail = (EditText) findViewById(R.id.editEmail);
        editPassword = (EditText) findViewById(R.id.editPassword);
        editAgain = (EditText) findViewById(R.id.aginPassword);
        btnRegister = (TextView) findViewById(R.id.btnRegister);
        txtCode = (TextView) findViewById(R.id.txtCode);
        editCode = (EditText) findViewById(R.id.editCode);
        editUserName.addTextChangedListener(textWatcher);
        //editEmail.addTextChangedListener(textWatcher);
        editPassword.addTextChangedListener(textWatcher);
        //editAgain.addTextChangedListener(textWatcher);
        findViewById(R.id.txtLogin).setOnClickListener(this);
        txtCode.setOnClickListener(this);

        tvContract = (TextView) findViewById(R.id.tvContract);
        cbContract = (CheckBox) findViewById(R.id.cbContract);
        panelContract = findViewById(R.id.panelContract);
        panelContract.setOnClickListener(this);
        tvContract.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG );
    }

    @Override
    public void initData() {

    }

    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            userName = editUserName.getText().toString().trim();
            password = editPassword.getText().toString().trim();
            //e_mail = editEmail.getText().toString().trim();
            //again = editAgain.getText().toString().trim();
            if (!userName.equals("") && !password.equals("")
                //&& !again.equals("")
                    ) {
//                btnRegister.setTextColor(getResources().getColor(R.color.white));
//                btnRegister.setBackgroundResource(R.drawable.login_on_bg);
                btnRegister.setClickable(true);
                btnRegister.setOnClickListener(RegisterActivity.this);
            } else {
//                btnRegister.setTextColor(getResources().getColor(R.color.gary_text));
//                btnRegister.setBackgroundResource(R.drawable.login_off_bg);
                btnRegister.setClickable(false);
            }
        }

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
        }
    };
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.fl_Left:
                KeyBoardUtils.closeKeybord(this);
                break;
            case R.id.btnRegister:
                prepare();
                break;
            case R.id.txtCode:
                if (null == userName || !CheckUtil.isMobileNO(userName) ) {
                    Utils.showToast($this, "请输入正确的手机号");
                    return;
                } else {
                    timer = new Timer();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            startime--;
                            Bundle bundle = new Bundle();
                            bundle.putInt("code", startime);
                            Message mag = new Message();
                            mag.setData(bundle);
                            han.sendMessage(mag);
                        }
                    }, startime, 1000);
                }
                sendCode();
                break;
            case R.id.txtLogin:
                LoginActivity.logout(context);
                break;
            case R.id.panelContract:
                RegisterProtocolActivity.startActivity((Activity) context,INTENT_WEB);
                break;
        }
    }

    private void sendCode() {
        presenter.setSendCodeView($this, userName, txtCode.getText().toString());
    }

    private Handler han = new Handler() {
        public void handleMessage(Message msg) {
            Bundle bundle = msg.getData();
            int s = bundle.getInt("code");
            if (s < 0) {
                timer.cancel();
                txtCode.setClickable(true);
                txtCode.setText("获取验证码");
                txtCode.setTextColor(getResources().getColor(R.color.colorPrimary));
                txtCode.setBackgroundResource(R.drawable.x_shape_green_border);
                startime = 60;
            } else {
                txtCode.setText("剩余时间:" + s);
                txtCode.setTextColor(getResources().getColor(R.color.gray));
                txtCode.setClickable(false);
                txtCode.setBackgroundResource(R.drawable.x_shape_gray_border_r20);
            }
        }

    };

    private void prepare() {
        if (!CheckUtil.isMobileNO(editUserName.getText().toString())) {
            Utils.showToast(context, "请填写正确手机号");
            return;
        }
        if (!editAgain.getText().toString().equals(password)){
            Utils.showToast(context,"两次输入密码不一致");
            return;
        }
        // submitData();
        if (!cbContract.isChecked()){
            Utils.showToast(context,"请确认注册协议");
            return;
        }
        ProtectedPasswordActivity.startActivity($this);
    }

    private void getRequest(String payPassword) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("phone", userName);
        map.put("password", password);
        map.put("identifyingCode", editCode.getText().toString().trim());
        map.put("payPwd",payPassword);
        OkHttpClientManager.postAsyn(context, ConfigValue.API_URL + "/user/phone/customer/registerCustomer",
                map, new BaseDelegate.ResultCallback<StringBean>() {
                    @Override
                    public void onError(com.squareup.okhttp.Request request, Object tag, Exception e) {
                        Utils.showToast(context, ExceptionHelper.getMessage(e, context));
                    }

                    @Override
                    public void onResponse(StringBean response, Object tag) {
                        if (response.getCode() == RESPONSE_CODE_SUC) {

                            presenter.loadLogin(context, userName, password, "0");

                        }
                        Utils.showToast(context, response.getMessage());
                    }
                }, true);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PAGE_PROTECTED_PASSWORD && resultCode == RESULT_OK){
            String payPassword = data.getStringExtra(KEY_PARAM);
            if (TextUtils.isEmpty(payPassword)){
                Utils.showToast($this,"密码设置有误");
                return;
            }
            getRequest(payPassword);
        }

        if (requestCode == INTENT_WEB && resultCode == RESULT_OK){
            cbContract.setChecked(true);
        }else if(requestCode == INTENT_WEB && resultCode == RESULT_FIRST_USER){
            cbContract.setChecked(false);
        }
    }

    @Override
    public void showProgress() {
        super.showProgress($this);
    }
}
